package com.sca.schedule.entity;

import com.sca.schedule.config.RabbitConfig;
import com.sca.schedule.utils.ApplicationContextHelper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author liuxianfei
 * @since 2020/11/20 13:30
 */
@Slf4j
@Setter
@Getter
public class SimpleTimerJob extends QuartzJobBean {

    private JobDetail jobDetail;
    private Trigger trigger;

    private SimpleTimerJob() {
    }

    public static SimpleTimerJob newInstance(Map<String, Serializable> params) {
        SimpleTimerJob job = new SimpleTimerJob();
        LocalDateTime triggerAt = (LocalDateTime) params.get("triggerAt");
        long startAtTime = triggerAt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        // 任务名称
        String name = UUID.randomUUID().toString();
        // 任务所属分组
        String group = SimpleTimerJob.class.getCanonicalName();
        // 创建任务
        JobDetail jobDetail = JobBuilder.newJob(SimpleTimerJob.class).withIdentity(name, group).build();
        jobDetail.getJobDataMap().put("params", params);
        // 创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).startAt(new Date(startAtTime)).build();
        job.setJobDetail(jobDetail);
        job.setTrigger(trigger);
        return job;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void executeInternal(JobExecutionContext context) {
        Map<String, Serializable> params = (Map<String, Serializable>) context.getJobDetail().getJobDataMap().get("params");
        JobKey jobKey = context.getJobDetail().getKey();
        log.info("触发定时任务，jobKey=[{}] dataMap=[{}]", jobKey, params);

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        RabbitTemplate mq = ApplicationContextHelper.context.getBean(RabbitTemplate.class);
        mq.convertAndSend(RabbitConfig.EXCHG_SCHEDULE, RabbitConfig.RTKEY_WAIT_EXEC, params, correlationData);
    }

}
